package LearnDataStructure.a_线性结构.例题;

/**
 * @version: 1.0
 * @Author: wuqiu
 * @date: 2023-07-03 13:52
 * @description: LeetcodeLearnAlgorithm -> LearnDataStructure.a_线性结构.例题
 *

 * 实现一个算法，删除单向链表中间的某个结点，假定你只能访问该结点。
 * 示例：
 * 输入单向链表a->b->c->d->e中的节点c
 * 结果：不返回任何数据，但该链表变为a->b->d->e
 *
给定待删除的节点，请执行删除操作，若该节点为尾节点，返回false，否则返回true
 */
public class c_删除单向链表的给定节点 {
    /*
    与其说是删除，不如说是目标数据覆盖
     */
    public static void main(String[] args) {
        c_删除单向链表的给定节点 test = new c_删除单向链表的给定节点();
        int[] arr = new int[]{9, 8, 7, 6, 6, 4, 2, 11, 11, 3, 4};
        test.useCover(arr,1);
    }

    public void useCover(int[] arr, int target) {
        if (arr.length == 0 || target < 0 || target > arr.length) {
            System.out.println("输入数据有误");
            return;
        }
        if (arr.length == 1) {
            System.out.println(true);
            System.out.println();
            return;
        }
        CaseNode head = new CaseNode(arr[0]);
        CaseNode p = head;
        CaseNode targetElement = null;
        if (target == 0) {
            targetElement = head;
        }
        for (int i = 1; i < arr.length; i++) {
            if (i != target) {
                p.next = new CaseNode(arr[i]);
            } else {
                p.next = new CaseNode(arr[i]);
                targetElement = p.next;
            }
            p = p.next;
        }
        boolean flag = cover(targetElement);
        System.out.println(flag);
        CaseNode temp = head;
        while (temp != null) {
            System.out.println(temp.data);
            temp = temp.next;
        }
    }

    public boolean cover(CaseNode targetElement) {
        if (targetElement.next == null) {
            return false;
        }
        targetElement.data = targetElement.next.data;
        targetElement.next = targetElement.next.next;//跨越后继
        // targetElement.next.next = null;
        return true;
    }
}
